package com.campus.food.controller;

import com.campus.food.model.entity.Food;
import com.campus.food.service.FoodService;
import com.campus.food.util.Result;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 菜品控制器
 * 处理菜品相关的HTTP请求
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/foods")
@Validated
public class FoodController {
    
    @Autowired
    private FoodService foodService;
    
    /**
     * 添加菜品（商家端）
     * POST /api/foods
     */
    @PostMapping
    public Result<Food> addFood(@Valid @RequestBody Food food) {
        try {
            Food savedFood = foodService.addFood(food);
            return Result.success("菜品添加成功", savedFood);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("添加菜品失败，请稍后重试");
        }
    }
    
    /**
     * 根据ID获取菜品信息
     * GET /api/foods/{id}
     */
    @GetMapping("/{id}")
    public Result<Food> getFoodById(@PathVariable @NotNull Long id) {
        try {
            Food food = foodService.getFoodById(id);
            return Result.success(food);
        } catch (BusinessException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取菜品信息失败");
        }
    }
    
    /**
     * 更新菜品信息（商家端）
     * PUT /api/foods/{id}
     */
    @PutMapping("/{id}")
    public Result<String> updateFood(@PathVariable @NotNull Long id,
                                   @RequestBody Food food) {
        try {
            food.setId(id);
            boolean success = foodService.updateFood(food);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新菜品信息失败");
        }
    }
    
    /**
     * 更新菜品状态（商家端）
     * PUT /api/foods/{id}/status
     */
    @PutMapping("/{id}/status")
    public Result<String> updateFoodStatus(@PathVariable @NotNull Long id,
                                         @RequestParam @NotNull Integer status,
                                         @RequestParam @NotNull Long merchantId) {
        try {
            boolean success = foodService.updateFoodStatus(id, status, merchantId);
            if (success) {
                String message = status == 1 ? "菜品已上架" : "菜品已下架";
                return Result.success(message);
            } else {
                return Result.error("状态更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新菜品状态失败");
        }
    }
    
    /**
     * 删除菜品（商家端）
     * DELETE /api/foods/{id}
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteFood(@PathVariable @NotNull Long id,
                                   @RequestParam @NotNull Long merchantId) {
        try {
            boolean success = foodService.deleteFood(id, merchantId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("删除菜品失败");
        }
    }
    
    /**
     * 根据商家ID获取菜品列表（商家端）
     * GET /api/foods/merchant/{merchantId}
     */
    @GetMapping("/merchant/{merchantId}")
    public Result<List<Food>> getFoodsByMerchantId(@PathVariable @NotNull Long merchantId,
                                                  @RequestParam(required = false) Integer status) {
        try {
            List<Food> foods = foodService.getFoodsByMerchantId(merchantId, status);
            return Result.success(foods);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取菜品列表失败");
        }
    }
    
    /**
     * 分页获取商家菜品列表（商家端）
     * GET /api/foods/merchant/{merchantId}/page
     */
    @GetMapping("/merchant/{merchantId}/page")
    public Result<List<Food>> getFoodListByMerchant(@PathVariable @NotNull Long merchantId,
                                                   @RequestParam(defaultValue = "1") int page,
                                                   @RequestParam(defaultValue = "10") int size,
                                                   @RequestParam(required = false) String name,
                                                   @RequestParam(required = false) String category,
                                                   @RequestParam(required = false) Integer status) {
        try {
            List<Food> foods = foodService.getFoodListByMerchant(merchantId, page, size, name, category, status);
            long total = foodService.getFoodCountByMerchant(merchantId, name, category, status);
            return Result.success(foods, total);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取菜品列表失败");
        }
    }
    
    /**
     * 分页获取菜品列表（用户端）
     * GET /api/foods/user/{merchantId}
     */
    @GetMapping("/user/{merchantId}")
    public Result<List<Food>> getFoodListForUser(@PathVariable @NotNull Long merchantId,
                                                @RequestParam(defaultValue = "1") int page,
                                                @RequestParam(defaultValue = "10") int size,
                                                @RequestParam(required = false) String name,
                                                @RequestParam(required = false) String category) {
        try {
            List<Food> foods = foodService.getFoodListForUser(merchantId, page, size, name, category);
            long total = foodService.getFoodCountForUser(merchantId, name, category);
            return Result.success(foods, total);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取菜品列表失败");
        }
    }
    
    /**
     * 根据分类获取菜品列表
     * GET /api/foods/category/{merchantId}/{category}
     */
    @GetMapping("/category/{category}/{merchantId}")
    public Result<List<Food>> getFoodsByCategory(@PathVariable String category,@PathVariable @NotNull Long merchantId
                                               ) {
        try {
            List<Food> foods = foodService.getFoodsByCategory(merchantId, category);
            return Result.success(foods);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取菜品列表失败");
        }
    }
    
    /**
     * 获取菜品分类列表
     * GET /api/foods/categories
     */
    @GetMapping("/categories")
    public Result<List<String>> getFoodCategories(@RequestParam(required = false) Long merchantId) {
        try {
            List<String> categories = foodService.getFoodCategories(merchantId);
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error("获取分类列表失败");
        }
    }
    
    /**
     * 获取商家菜品分类列表
     * GET /api/foods/categories/{merchantId}
     */
    @GetMapping("/categories/{merchantId}")
    public Result<List<String>> getMerchantFoodCategories(@PathVariable @NotNull Long merchantId) {
        try {
            List<String> categories = foodService.getFoodCategories(merchantId);
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error("获取分类列表失败");
        }
    }
    
    /**
     * 获取热销菜品
     * GET /api/foods/hot/{merchantId}
     */
    @GetMapping("/hot/{merchantId}")
    public Result<List<Food>> getHotFoods(@PathVariable @NotNull Long merchantId,
                                        @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Food> foods = foodService.getHotFoods(merchantId, limit);
            return Result.success(foods);
        } catch (Exception e) {
            return Result.error("获取热销菜品失败");
        }
    }
    
    /**
     * 批量获取菜品信息
     * POST /api/foods/batch
     */
    @PostMapping("/batch")
    public Result<List<Food>> getFoodsByIds(@RequestBody List<Long> ids) {
        try {
            List<Food> foods = foodService.getFoodsByIds(ids);
            return Result.success(foods);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取菜品信息失败");
        }
    }
    
    /**
     * 增加菜品销量
     * PUT /api/foods/{id}/sales
     */
    @PutMapping("/{id}/sales")
    public Result<String> increaseSales(@PathVariable @NotNull Long id,
                                      @RequestParam @NotNull Integer quantity) {
        try {
            boolean success = foodService.increaseSales(id, quantity);
            if (success) {
                return Result.success("销量更新成功");
            } else {
                return Result.error("销量更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新销量失败");
        }
    }
    
    /**
     * 批量删除菜品（商家端）
     * DELETE /api/foods/batch
     */
    @DeleteMapping("/batch")
    public Result<String> deleteFoodBatch(@RequestParam List<Long> ids,
                                        @RequestParam @NotNull Long merchantId) {
        try {
            boolean success = foodService.deleteFoodBatch(ids, merchantId);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("批量删除菜品失败");
        }
    }
    
    /**
     * 搜索菜品
     * GET /api/foods/search
     */
    @GetMapping("/search")
    public Result<List<Food>> searchFoods(@RequestParam(required = false) String keyword,
                                        @RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "10") int size,
                                        @RequestParam(required = false) Long merchantId,
                                        @RequestParam(required = false) String category,
                                        @RequestParam(required = false) Double minPrice,
                                        @RequestParam(required = false) Double maxPrice) {
        try {
            List<Food> foods = foodService.searchFoods(keyword, page, size, merchantId, category, minPrice, maxPrice);
            return Result.success(foods);
        } catch (Exception e) {
            return Result.error("搜索菜品失败");
        }
    }
    
    /**
     * 获取推荐菜品
     * GET /api/foods/recommended
     */
    @GetMapping("/recommended")
    public Result<List<Food>> getRecommendedFoods(@RequestParam(required = false) Long merchantId,
                                                @RequestParam(defaultValue = "10") int limit) {
        try {
            List<Food> foods = foodService.getRecommendedFoods(merchantId, limit);
            return Result.success(foods);
        } catch (Exception e) {
            return Result.error("获取推荐菜品失败");
        }
    }
    
    /**
     * 批量更新菜品状态（商家端）
     * PUT /api/foods/batch/status
     */
    @PutMapping("/batch/status")
    public Result<String> updateFoodStatusBatch(@RequestParam List<Long> ids,
                                              @RequestParam @NotNull Integer status,
                                              @RequestParam @NotNull Long merchantId) {
        try {
            boolean success = foodService.updateFoodStatusBatch(ids, status, merchantId);
            if (success) {
                String message = status == 1 ? "批量上架成功" : "批量下架成功";
                return Result.success(message);
            } else {
                return Result.error("批量状态更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("批量更新菜品状态失败");
        }
    }
    
    /**
     * 获取菜品销量统计
     * GET /api/foods/sales-stats/{merchantId}
     */
    @GetMapping("/sales-stats/{merchantId}")
    public Result<List<Food>> getFoodSalesStats(@PathVariable @NotNull Long merchantId,
                                               @RequestParam(required = false) String startDate,
                                               @RequestParam(required = false) String endDate) {
        try {
            List<Food> stats = foodService.getFoodSalesStats(merchantId, startDate, endDate);
            return Result.success(stats);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取销量统计失败");
        }
    }
    
    /**
     * 获取所有菜品列表（管理员专用）
     * GET /api/foods/admin
     */
    @GetMapping("/admin")
    public Result<List<Food>> getAllFoods(@RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "10") int size,
                                        @RequestParam(required = false) Long merchantId,
                                        @RequestParam(required = false) String category,
                                        @RequestParam(required = false) Integer status) {
        try {
            List<Food> foods = foodService.getAllFoods(page, size, merchantId, category, status);
            return Result.success(foods);
        } catch (Exception e) {
            return Result.error("获取菜品列表失败");
        }
    }
    
    /**
     * 获取商家菜品总数
     * GET /api/foods/merchant/{merchantId}/count
     */
    @GetMapping("/merchant/{merchantId}/count")
    public Result<Long> getFoodCountByMerchant(@PathVariable @NotNull Long merchantId,
                                             @RequestParam(required = false) String name,
                                             @RequestParam(required = false) String category,
                                             @RequestParam(required = false) Integer status) {
        try {
            long count = foodService.getFoodCountByMerchant(merchantId, name, category, status);
            return Result.success(count);
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取菜品数量失败");
        }
    }
} 